<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片 -->
    <el-card>
      <!-- 添加角色 -->
      <el-row :gutter="20">
        <el-col :span="4">
          <el-button type="primary" @click="addRoles = true">
            添加角色
          </el-button>
        </el-col>
      </el-row>
      <!-- 角色列表区 -->
      <el-table :data="rolesList" border>
        <el-table-column type="expand">
          <template #default="scope">
            <el-row
              v-for="(item1, index1) in scope.row.children"
              :key="item1.id"
              :class="['bdbottom', index1 === 0 ? 'bdtop' : '', 'vcenter']"
            >
              <!-- 一级权限 -->
              <!-- 第一列 -->
              <el-col :span="5">
                <el-tag
                  type="primary"
                  closable
                  @close="removeRightById(scope.row, item1.id)"
                >
                  {{ item1.authName }}
                </el-tag>
                <el-icon><caret-right /></el-icon>
              </el-col>
              <!-- 二三级权限 -->
              <!-- 第二列 -->
              <el-col :span="19">
                <!-- row行,循环children有多少给item2,就有多少行 -->
                <!-- 循环行 -->
                <el-row
                  v-for="(item2, index2) in item1.children"
                  :key="item2.id"
                  :class="[index2 === 0 ? '' : 'bdtop', 'vcenter']"
                >
                  <!-- 将item2.authName 渲染到每一列 -->
                  <el-col :span="6">
                    <el-tag
                      type="success"
                      closable
                      @close="removeRightById(scope.row, item2.id)"
                      >{{ item2.authName }}
                    </el-tag>
                    <el-icon><caret-right /></el-icon>
                  </el-col>
                  <el-col :span="18">
                    <el-tag
                      v-for="item3 in item2.children"
                      :key="item3.id"
                      type="warning"
                      closable
                      @close="removeRightById(scope.row, item3.id)"
                    >
                      {{ item3.authName }}
                    </el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index" width="50" />
        <el-table-column prop="roleName" label="角色名称" />
        <el-table-column prop="roleDesc" label="角色描述"/>
        <el-table-column prop="操作" label="操作"  width="300" >
          <template #default="scope">
            <!-- 编辑按钮 -->
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="editRoles(scope.row.id)"
              >编辑</el-button
            >
            <!-- 删除按钮 -->
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="deleteRoles(scope.row.id)"
              >删除</el-button
            >
            <!-- 分配角色按钮 -->
            <el-button
              type="warning"
              icon="el-icon-setting"
              size="mini"
              @click="showSetRightDialog(scope.row)"
              >分配权限</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <!-- 添加角色 -->
      <el-dialog
        :visible.sync="addRoles"
        title="添加用户"
        width="50%"
        @close="addDialogClosed"
      >
        <!-- 内容主体区 -->
        <el-form
          ref="addRolesFormRef"
          label-width="90px"
          :model="addRolesForm"
          :rules="addRolesFormRulse"
        >
          <el-form-item label="角色名称" prop="roleName">
            <el-input v-model="addRolesForm.roleName"></el-input>
          </el-form-item>
          <el-form-item label="角色描述" prop="roleDesc">
            <el-input v-model="addRolesForm.roleDesc"></el-input>
          </el-form-item>
        </el-form>
        <!-- 底部区域 -->
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="addRoles = false">取消</el-button>
            <el-button type="primary" @click="addnewRoles">确定</el-button>
          </span>
        </template>
      </el-dialog>
      <!-- 编辑角色 -->
      <el-dialog :visible.sync="editDialogVisible" title="修改角色信息" width="50%">
        <!-- 内容主体区 -->
        <el-form
          ref="editFormRef"
          label-width="90px"
          :model="editRolesForm"
          :rules="addRolesFormRulse"
        >
          <el-form-item label="角色名称" prop="roleName">
            <el-input v-model="editRolesForm.roleName"></el-input>
          </el-form-item>
          <el-form-item label="角色描述" prop="roleDesc">
            <el-input v-model="editRolesForm.roleDesc"></el-input>
          </el-form-item>
        </el-form>
        <!-- 底部区域 -->
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="editDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="editNewRoles">确定</el-button>
          </span>
        </template>
      </el-dialog>
      <!-- 分配角色 -->
      <el-dialog
        :visible.sync="setRightDialogVisible"
        title="分配权限"
        width="50%"
        @close="setRightDialogClosed"
      >
        <!-- 内容主体区 -->
        <el-tree
          ref="refTree"
          :data="rightList"
          :props="treeProps"
          node-key="id"
          show-checkbox
          default-expand-all
          :default-checked-keys="defkeys"
        />
        <!-- 底部区域 -->
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="setRightDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="allotRights">确定</el-button>
          </span>
        </template>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
import { MessageBox, Message} from "element-ui";
export default {
  name: "Roles",
  data() {
    return {
      defkeys: [],
      keysId: "",
      rolesList: [],
      rightList: [],
      treeProps: {
        children: "children",
        label: "authName",
      },
      addRoles: false,
      editDialogVisible: false,
      setRightDialogVisible: false,
      addRolesForm: {
        roleName: "",
        roleDesc: "",
      },
      editRolesForm: {},
      addRolesFormRulse: {
        roleName: [
          {
            required: true,
            message: "请输入角色名称",
            trigger: "blur",
          },
          {
            min: 2,
            max: 10,
            message: "长度在2到10个字符之间",
            trigger: "blur",
          },
        ],
        roleDesc: [
          {
            required: true,
            message: "请输入角色描述",
            trigger: "blur",
          },
          {
            min: 3,
            max: 15,
            message: "长度在3到15个字符之间",
            trigger: "blur",
          },
        ],
      },
    };
  },
  created() {
    this.getRolesList();
  },
  methods: {
    // 获取角色列表
    async getRolesList() {
      const { data: res } = await this.$http.get("/roles");
      if (res.meta.status !== 200)
        return this.$message.error("获取角色列表失败");
      this.rolesList = res.data;
    },
    // 关闭弹出框重置添加用户表单
    addDialogClosed() {
      this.$refs.addRolesFormRef.resetFields();
    },
    // 点击确定添加角色
    addnewRoles() {
      this.$refs.addRolesFormRef.validate(async (valid) => {
        if (!valid) return;
        const { data: res } = await this.$http.post(
          "/roles",
          this.addRolesForm
        );
        if (res.meta.status !== 201) return this.$message.error("添加角色失败");
        this.$message.success("添加角色成功");
        this.addRoles = false;
        this.getRolesList();
      });
    },
    // 点击编辑按钮
    async editRoles(id) {
      const { data: res } = await this.$http.get("/roles/" + id);
      if (res.meta.status !== 200) {
        return this.$message.error("查询角色信息失败");
      }
      this.editRolesForm = res.data;
      this.editDialogVisible = true;
    },
    // 点击确定修改角色按钮
    editNewRoles() {
      this.$refs.editFormRef.validate(async (valid) => {
        // 如果验证失败之间return空
        if (!valid) return;
        // 如果验证成功就发起请求
        const { data: res } = await this.$http.put(
          "/roles/" + this.editRolesForm.roleId,
          {
            roleName: this.editRolesForm.roleName,
            roleDesc: this.editRolesForm.roleDesc,
          }
        );
        if (res.meta.status !== 200) return this.$message.error("编辑角色失败");
        this.$message.success("修改角色成功");
        this.editDialogVisible = false;
        this.getRolesList();
      });
    },
    // 点击删除按钮
    async deleteRoles(id) {
      const res = await MessageBox.confirm(
        "此操作将永久删除该角色,是否继续?",
        "警告",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch(() => {
        Message({
          type: "info",
          message: "已取消删除",
        });
      });
      // 如果用户确认了删除,返回字符串confirm
      if (res === "confirm") {
        const { data: res } = await this.$http.delete("/roles/" + id);
        if (res.meta.status !== 200) return this.$message.error("删除角色失败");
        Message({
          type: "success",
          message: "删除角色成功",
        });
        this.getRolesList();
      }
    },
    // 点击删除权限
    async removeRightById(role, rightId) {
      const Messageres = await MessageBox.confirm(
        "此操作将永久删除该权限,是否继续?",
        "警告",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch(() => {
        Message({
          type: "info",
          message: "已取消删除",
        });
      });
      // 如果用户确认了删除,返回字符串confirm
      if (Messageres === "confirm") {
        const { data: res } = await this.$http.delete(
          `/roles/${role.id}/rights/${rightId}`
        );
        if (res.meta.status !== 200) return this.$message.error("删除权限失败");
        role.children = res.data;
        // console.log(this.rightList);
        // console.log(role.children);
      }
    },
    // 点击弹出分配权限框
    async showSetRightDialog(role) {
      const { data: res } = await this.$http.get("/rights/tree");
      // console.log(res);
      if (res.meta.status !== 200)
        return this.$message.error("获取分配权限失败");
      this.rightList = res.data;
      this.keysId = role.id;
      this.getLeafKeys(role, this.defkeys);
      this.setRightDialogVisible = true;
    },
    // 递归获取三级节点
    getLeafKeys(node, arr) {
      if (!node.children) return arr.push(node.id);
      node.children.forEach((item) => {
        this.getLeafKeys(item, arr);
      });
    },
    // 关闭分配权限列表，清空defeys数组
    setRightDialogClosed() {
      this.defkeys = [];
    },
    // 点击确定按钮，确定分配权限
    async allotRights() {
      const keys = [
        ...this.$refs.refTree.getHalfCheckedKeys(),
        ...this.$refs.refTree.getCheckedKeys(),
      ];
      const strKeys = keys.join(",");
      console.log(strKeys);
      const { data: res } = await this.$http.post(
        `/roles/${this.keysId}/rights`,
        {
          rids: strKeys,
        }
      );
      if (res.meta.status !== 200)
        return this.$message.error("更新分配权限失败");
      this.$message.success("更新分配权限成功");
      this.getRolesList();
      this.setRightDialogVisible = false;
    },
  },
};
</script>

<style lang='less' scoped>
.el-tag {
  margin: 7px;
}
.bdtop {
  border-top: 1px solid #eee;
}
.bdbottom {
  border-bottom: 1px solid #eee;
}
.vcenter {
  display: flex;
  align-items: center;
}
</style>